package cn.yuanqiao.archive.utils;

import cn.yuanqiao.archive.appManager.domain.YqSy;
import cn.yuanqiao.archive.appManager.service.ITenantSysConfigService;
import com.lowagie.text.Document;
import com.lowagie.text.Element;
import com.lowagie.text.pdf.*;
import org.apache.commons.io.output.ByteArrayOutputStream;
import org.apache.poi.sl.usermodel.PictureData;
import org.apache.poi.xslf.usermodel.XMLSlideShow;
import org.apache.poi.xslf.usermodel.XSLFPictureShape;
import org.apache.poi.xslf.usermodel.XSLFSlide;
import org.springframework.beans.factory.annotation.Autowired;

import javax.imageio.ImageIO;
import javax.swing.*;
import java.awt.*;
import java.awt.font.FontRenderContext;
import java.awt.geom.Rectangle2D;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;

/**
 * 下载 docx doc 文件 添加水印
 *
 * @author Administrator
 */
public class FileWaterMark {
    // 水印透明度
    private static float alpha = 0.5f;
    // 水印之间的间隔
    private static final int XMOVE = 200;
    // 水印之间的间隔
    private static final int YMOVE = 200;

    @Autowired
    private ITenantSysConfigService sysConfigService;

//    public enum FontType {
//
//        SONG("宋体"),
//        FANGSONG("仿宋"),
//        HEITI("黑体"),
//        KAITI("楷体");
//
//        private final String value;
//
//        FontType(String value) {
//            this.value = value;
//        }
//
//        public static FontType fromString(String fontStr) {
//            for (FontType fontType : values()) {
//                if (fontType.value.equals(fontStr)) {
//                    return fontType;
//                }
//            }
//            return null;
//        }
//
//    }


//	public static void setWatermark(String fileUrl,String outFile, Map map,HttpServletResponse response,String prefix) {
//		File inFile = new File(fileUrl);
//		String fileName = inFile.getName();
//		Document document = null;
//		FileInputStream fis = null;
//		BufferedInputStream bis = null;
//		BufferedOutputStream bos=null;
//		XMLSlideShow slideShow = null;
//		XSSFWorkbook workbook = null;
//		File file = new File(outFile);
//		try {
//			if(!file.exists()) {
//				file.getParentFile().mkdirs();
//				file.createNewFile();
//			}
//			if("docx".equals(prefix)||"doc".equals(prefix)) {
//				document = new Document();
//				document.loadFromFile(inFile.toString());
//				InsertTextWatermark(document.getSections().get(0),map);
//				document.saveToFile(outFile, FileFormat.Docx );
//				response.setContentType("application/octet-stream;charset=UTF-8");
//				String fileNamedoc = new String(fileName.getBytes("UTF-8"), "iso-8859-1");
//				response.addHeader("Content-Disposition", "attachment; filename = " + fileNamedoc);
//				fis = new FileInputStream(file);
//				bis = new BufferedInputStream(fis);
//				bos = new BufferedOutputStream(response.getOutputStream());
//				byte[] buf = new byte[4096];
//				int length = bis.read(buf);
//				//保存文件
//				while(length != -1){
//					bos.write(buf, 0, length);
//					length = bis.read(buf);
//				}
//				bos.flush();
//				bos.close();
//				bis.close();
//			}
//		}catch (Exception e) {
//			e.printStackTrace();
//		}finally {
//			if(bos!=null) {
//				try {
//					bos.close();
//				} catch (IOException e1) {
//					e1.printStackTrace();
//				}
//			}
//			if(bis!=null) {
//				try {
//					bis.close();
//				} catch (IOException e) {
//					e.printStackTrace();
//				}
//			}
//			if(fis!=null) {
//				try {
//					fis.close();
//				} catch (IOException e) {
//					e.printStackTrace();
//				}
//			}
//		}
//
//	}

    /**
     * 自定义方法插入文本水印并格式水印效果
     * word
     */
//	private static void InsertTextWatermark(Section section,Map map){
//		TextWatermark txtWatermark = new TextWatermark();
//		txtWatermark.setText(map.get("SYNR").toString());
//		txtWatermark.setFontSize(Float.valueOf(map.get("FONTSIZE").toString()));
//		String colorString = map.get("COLOR").toString();
//		String[] rgb = colorString.substring(4, colorString.length() - 1).split(",");
//		int red = Integer.parseInt(rgb[0].trim());
//		int green = Integer.parseInt(rgb[1].trim());
//		int blue = Integer.parseInt(rgb[2].trim());
//		Color color = new Color(red, green, blue);
//		txtWatermark.setColor(color);
//		txtWatermark.setLayout(WatermarkLayout.Diagonal);
//		section.getDocument().setWatermark(txtWatermark);
//	}
    /**
     * 获取水印文字图片流
     *
     * @param yqSy
     * @return
     */
    private static ByteArrayOutputStream getImage(YqSy yqSy) {
        ByteArrayOutputStream os = new ByteArrayOutputStream();
        try {
            // 导出到字节流B
            BufferedImage image = createWaterMarkImageBig(yqSy);
            ImageIO.write(image, "png", os);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return os;
    }
    /**
     * 根据文字生成水印图片（大号 平铺）
     *
     * @param yqSy
     * @return
     */
    public static BufferedImage createWaterMarkImageBig(YqSy yqSy) {
        Integer width = 1000;
        Integer height = 800;
        BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);// 获取bufferedImage对象
        Font font = new Font(yqSy.getFont(), Font.PLAIN, Integer.valueOf(yqSy.getFontsize()));
        Graphics2D g2d = image.createGraphics();
        image = g2d.getDeviceConfiguration().createCompatibleImage(width, height, Integer.valueOf(yqSy.getTransparency()));
        g2d.dispose();
        g2d = image.createGraphics();
        //设置字体颜色和透明度
        String colorString = yqSy.getColor();
        String[] rgb = colorString.substring(4, colorString.length() - 1).split(",");
        int red = Integer.parseInt(rgb[0].trim());
        int green = Integer.parseInt(rgb[1].trim());
        int blue = Integer.parseInt(rgb[2].trim());
        Color color = new Color(red, green, blue);
        g2d.setColor(color);
        //设置字体
        g2d.setStroke(new BasicStroke(1));
        //设置字体类型  加粗 大小
        g2d.setFont(font);
        //设置倾斜度
        int jiaodu = yqSy.getRotate()==0?0:45;
        g2d.rotate(Math.toRadians(jiaodu), (double) image.getWidth() / 2, (double) image.getHeight() / 2);

        FontRenderContext context = g2d.getFontRenderContext();
        Rectangle2D bounds = font.getStringBounds(yqSy.getSynr(), context);
        double x = (width - bounds.getWidth()) / 2;
        double y = (height - bounds.getHeight()) / 2;
        double ascent = -bounds.getY();
        double baseY = y + ascent;
        //写入水印文字原定高度过小，所以累计写水印，增加高度
        g2d.drawString(yqSy.getSynr(), (int) x, (int) baseY);
        //设置透明度
        g2d.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER));
        //释放对象
        g2d.dispose();
        return image;
    }

    /**
     * @param srcImgPath 源图片路径
     * @param tarImgPath 保存的图片路径
     * @param yqSy       水印内容
     */
    public static void addPictureWaterMark(String srcImgPath, String tarImgPath, YqSy yqSy) {
        FileOutputStream outImgStream = null;
        try {
            if(!new File(tarImgPath).getParentFile().exists()){
                new File(tarImgPath).getParentFile().mkdirs();
            }
            // 读取原图片信息
            File srcImgFile = new File(srcImgPath);// 得到文件
            Image srcImg = ImageIO.read(srcImgFile);// 文件转化为图片
            int srcImgWidth = srcImg.getWidth(null);// 获取图片的宽
            int srcImgHeight = srcImg.getHeight(null);// 获取图片的高
            int jiaodu = yqSy.getRotate()==0 ? 0 : 45;
            String synr = yqSy.getSynr();
            // 加水印
            BufferedImage bufImg = new BufferedImage(srcImgWidth, srcImgHeight,
                    BufferedImage.TYPE_INT_RGB);
            Graphics2D g = bufImg.createGraphics();
            // 设置对线段的锯齿状边缘处理
            g.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BILINEAR);
            g.drawImage(srcImg, 0, 0, srcImgWidth, srcImgHeight, null);
            // 设置水印旋转

            g.rotate(Math.toRadians(jiaodu),
                    (double) bufImg.getWidth() / 2,
                    (double) bufImg.getHeight() / 2);

            //颜色
            String colorString = yqSy.getColor();
            String[] rgb = colorString.substring(4, colorString.length() - 1).split(",");
            int red = Integer.parseInt(rgb[0].trim());
            int green = Integer.parseInt(rgb[1].trim());
            int blue = Integer.parseInt(rgb[2].trim());
            Color color = new Color(red, green, blue);

            g.setColor(color); // 根据图片的背景设置水印颜色

            //字体设置，支持中文
            String fontName = yqSy.getFont();
            int fontSize = Integer.parseInt(yqSy.getFontsize());
            Font font = new Font(fontName, Font.PLAIN, fontSize);
            g.setFont(font); // 设置字体
            // 设置水印文字透明度
            alpha = Float.valueOf(yqSy.getTransparency()) / 100;
            g.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_ATOP, alpha));

            //根据不同的像素判断多个水印还是单个水印300*300
            if (yqSy.getLine()==1) {
//            if (srcImgWidth > 300 && srcImgHeight > 300) {
                //多个水印
                // 设置水印的坐标
                int x = -srcImgWidth / 2;
                int y = -srcImgHeight / 2;
                int markWidth = font.getSize() * getTextLength(synr);// 字体长度
                int markHeight = font.getSize();// 字体高度
                // 循环添加水印
                while (x < srcImgWidth * 1.5) {
                    y = -srcImgHeight / 2;
                    while (y < srcImgHeight * 1.5) {
                        g.drawString(synr, x, y);
                        y += markHeight + YMOVE;
                    }
                    x += markWidth + XMOVE;
                }
            } else {
                //单个水印
                int x = (srcImgWidth - getWatermarkLength(synr, g)) / 2;
                int y = srcImgHeight / 2;
                g.drawString(synr, x, y);
            }
            g.dispose();
            // 输出图片
            outImgStream = new FileOutputStream(tarImgPath);
            String formatName = srcImgPath.substring(srcImgPath.lastIndexOf(".") + 1);
            ImageIO.write(bufImg, formatName, outImgStream);
            outImgStream.flush();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (outImgStream != null) {
                try {
                    outImgStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
    /**
     * PPT设置水印
     *
     * @param path
     * @param targetpath
     * @param yqSy
     * @throws IOException
     */
    public static void setPPTWaterMark(String path, String targetpath, YqSy yqSy) {
        XMLSlideShow slideShow =null;
        try {
            slideShow = new XMLSlideShow(new FileInputStream(path));
        } catch (IOException e) {
            e.printStackTrace();
//            log.error("setPPTWaterMark fail:", e);
//            throw new MyException(ResultCode.FAILURE, "setPPTWaterMark fail:获取PPT文件失败");
        }
        ByteArrayOutputStream os = null;
        FileOutputStream out = null;
        try {
            //获取水印
            os = getImage(yqSy);
            PictureData pictureData1 = slideShow.addPicture(os.toByteArray(), PictureData.PictureType.PNG);
            for (XSLFSlide slide : slideShow.getSlides()) {
                XSLFPictureShape pictureShape = slide.createPicture(pictureData1);
//                pictureShape.setAnchor(new java.awt.Rectangle(250, 0, 500, 500));
                pictureShape.setAnchor(pictureShape.getAnchor());
            }
            out = new FileOutputStream(targetpath);
            slideShow.write(out);
        } catch (IOException e) {
            e.printStackTrace();
//            log.error("setPPTWaterMark fail:" + e);
//            throw new MyException(ResultCode.FAILURE, "setPPTWaterMark fail：生成ppt文件失败");
        } finally {
            if (slideShow != null) {
                try {
                    slideShow.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (out != null) {
                try {
                    out.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (os != null) {
                try {
                    os.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    /**
     * 获取水印文字总长度
     *
     * @param waterMarkContent 水印的文字
     * @param g
     * @return 水印文字总长度
     */
    public static int getWatermarkLength(String waterMarkContent, Graphics2D g) {
        return g.getFontMetrics(g.getFont()).charsWidth(waterMarkContent.toCharArray(), 0, waterMarkContent.length());
    }

    /**
     * 获取文本长度。汉字为1:1，英文和数字为2:1
     */
    private static int getTextLength(String text) {
        int length = text.length();
        for (int i = 0; i < text.length(); i++) {
            String s = String.valueOf(text.charAt(i));
            if (s.getBytes().length > 1) {
                length++;
            }
        }
        length = length % 2 == 0 ? length / 2 : length / 2 + 1;
        return length;
    }

    /**
     * 判断文件是否加密
     * @param file
     * @return
     */
    public static Boolean PdfIsEncryption(String file){
        PdfReader reader = null;
        try {
            String prefix = file.substring(file.lastIndexOf(".")+1);
            if ("pdf".equals(prefix)||"PDF".equals(prefix)){
                reader = new PdfReader(file);
                return reader.isEncrypted();
            }else {
                return false;
            }
        }catch (Exception e){
            e.printStackTrace();
            return true;
        }finally {
            if(reader !=null){
                reader.close();
            }
        }
// return true;
    }
    public static boolean check(String file) {
        PdfReader reader = null;

        boolean flag1 = false;
        int n = 0;
        try {
            Document document = new Document(new PdfReader(file).getPageSize(1));
            document.open();
             reader = new PdfReader(file);
            n = reader.getNumberOfPages();
            if (n != 0)
                flag1 = true;
            document.close();
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }finally {
            if(reader !=null){
                reader.close();
            }
        }
        return flag1;
    }

    public static boolean checkImage(String imagePath) {
       // boolean flag1 = false;
        File file = new File(imagePath);
        try {
            ImageIO.read(file);
            return true;
        } catch (IOException e) {
            return false;
        }
    }
//    public static void main(String[] args) {
//        String path="D:\\项目\\项目\\OCR\\测试数据\\1708426882473.jpg";
//        System.out.println(checkImage(path));
//
//    }

    /**
     * pdf 添加水印
     *
     * @param inputFile  服务器资源PDF文件地址
     * @param outputFile 添加水印后生成PDF存放的地址
     * @param yqSy       水印
     * @return
     */
    public static void pdfWaterMark(String inputFile, String outputFile, YqSy yqSy) {
//				{COLOR=rgb(255,255,255), TRANSPARENCY=21, ROTATE=0, LINE=1, SYNR=3, FONT=仿宋, SETUP=1, FONTSIZE=12}
        PdfReader reader = null;
        try {
            int interval = -5;
            int textH = 0;
            int textW = 0;
            FontMetrics metrics;
            reader = new PdfReader(inputFile);
            // PdfReader.unethicalreading = true;
            File file = new File(outputFile);
            if (!file.exists()) {
                file.getParentFile().mkdirs();
                file.createNewFile();
            }

//            String fontPath = SpringUtils.getBean(ITenantSysConfigService.class).selectConfigByKey("FONTPATH");
//            if (StringUtils.isNULL(fontPath)) {
//                throw new RuntimeException("没有在系统参数表配置添加字体文件保存路径FONTPATH字段");
//            }
            String fontPath = "/Fonts/";
            PdfStamper stamper = new PdfStamper(reader, new FileOutputStream(outputFile));
            //字体设置，支持中文
            String font = yqSy.getFont().trim();
//            FontType fontEnum = FontType.fromString(font);
            BaseFont base = null;
            try {
                if (null!=font){
                    switch (font) {
                        case "宋体":
                            // 设置字体为宋体
                            base = BaseFont.createFont(fontPath + "STSONG.TTF", BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED);
                            break;
                        case "仿宋":
                            // 设置字体为仿宋
                            base = BaseFont.createFont(fontPath + "simfang.ttf", BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED);
                            break;
                        case "黑体":
                            // 设置字体为黑体
                            base = BaseFont.createFont(fontPath + "simhei.ttf", BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED);
                            break;
                        case "楷体":
                            // 设置字体为楷体
                            base = BaseFont.createFont(fontPath + "simkai.ttf", BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED);
                            break;
                        default:
                            base = BaseFont.createFont("STSong-Light", "UniGB-UCS2-H", BaseFont.NOT_EMBEDDED);// 使用系统字体
                            break;
                    }
                }
//                if (null!=fontEnum){
//                    switch (fontEnum) {
//                        case SONG:
//                            // 设置字体为宋体
//                            base = BaseFont.createFont(fontPath + "STSONG.TTF", BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED);
//                            break;
//                        case FANGSONG:
//                            // 设置字体为仿宋
//                            base = BaseFont.createFont(fontPath + "simfang.ttf", BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED);
//                            break;
//                        case HEITI:
//                            // 设置字体为黑体
//                            base = BaseFont.createFont(fontPath + "simhei.ttf", BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED);
//                            break;
//                        case KAITI:
//                            // 设置字体为楷体
//                            base = BaseFont.createFont(fontPath + "simkai.ttf", BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED);
//                            break;
//                        default:
//                            base = BaseFont.createFont("STSong-Light", "UniGB-UCS2-H", BaseFont.NOT_EMBEDDED);// 使用系统字体
//                            break;
//                    }
//                }
//				if("宋体".contentEquals(font)) {
//					base = BaseFont.createFont(fontPath+"STSONG.TTF", BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED);
//				} else if("仿宋".contentEquals(font)) {
//					base = BaseFont.createFont(fontPath+"simfang.ttf", BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED);
//				} else if("黑体".contentEquals(font)) {
//					base = BaseFont.createFont(fontPath+"simhei.ttf", BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED);
//				} else if("楷体".contentEquals(font)) {
//					base = BaseFont.createFont(fontPath+"simkai.ttf", BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED);
//				} else {
//					base = BaseFont.createFont("STSong-Light","UniGB-UCS2-H", BaseFont.NOT_EMBEDDED);
////					base = BaseFont.createFont(fontPath+"STSONG.TTF", BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED);
//				}
            }
            catch (IOException ioException){
                if (base == null) {
                    // 使用默认字体
                    base = BaseFont.createFont("STSong-Light", "UniGB-UCS2-H", BaseFont.NOT_EMBEDDED);
//					base = BaseFont.createFont(fontPath+"STSONG.TTF", BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED);
                }
            } finally {
                if (base == null) {
                    // 使用默认字体
                    base = BaseFont.createFont("STSong-Light", "UniGB-UCS2-H", BaseFont.NOT_EMBEDDED);
//					base = BaseFont.createFont(fontPath+"STSONG.TTF", BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED);
                }
            }
            int total = reader.getNumberOfPages() + 1;//获取PDF页数
            PdfContentByte under;//水印文字相关
            com.lowagie.text.Rectangle pageRect = null;//定义矩形区域
            PdfGState gs = new PdfGState();//设置透明度
            // 设置透明度
            alpha = Float.valueOf(yqSy.getTransparency());
            //文字大小
            float fontsize = Float.valueOf(yqSy.getFontsize());
            //颜色
            String colorString = yqSy.getColor();
            String[] rgb = colorString.substring(4, colorString.length() - 1).split(",");
            int red = Integer.parseInt(rgb[0].trim());
            int green = Integer.parseInt(rgb[1].trim());
            int blue = Integer.parseInt(rgb[2].trim());
            Color color = new Color(red, green, blue);
            //水印内容
            String synr = yqSy.getSynr();
//			synr = new String(synr.getBytes("UTF-8"), "GB18030");
            int jiaodu = yqSy.getRotate() == 0 ? 0 : 45;
            String line = String.valueOf(yqSy.getLine());

            /** 添加一个水印 */
            for (int i = 1; i < total; i++) {
                pageRect = stamper.getReader().getPageSizeWithRotation(i);
                // 计算水印X,Y坐标
                float x = pageRect.getWidth() / 10 + 250;
                float y = pageRect.getHeight() / 10 + 300;
                // 获得PDF最顶层
                under = stamper.getOverContent(i);//在内容上方加水印
//				under = stamper.getUnderContent(i);//在内容下方加水印
                under.saveState();
                gs.setFillOpacity(alpha);//透明度
                under.setGState(gs);
                under.restoreState();
                under.beginText();
                under.setFontAndSize(base, fontsize);//水印文字大小
                under.setColorFill(color);//颜色
                // 水印文字成45度角倾斜
                if (line.equals("0")) {
                    under.showTextAligned(Element.ALIGN_CENTER, synr, x, y, jiaodu);

                } else {
                    JLabel label = new JLabel();
                    label.setText(synr);
                    metrics = label.getFontMetrics(label.getFont());
                    textH = metrics.getHeight();
                    textW = metrics.stringWidth(label.getText());
                    for (int height = interval + textH; height < pageRect.getHeight(); height = height + textH * 6) {
                        for (int width = interval + textW; width < pageRect.getWidth() + textW; width = width + textW) {
                            under.showTextAligned(Element.ALIGN_LEFT, synr, width - textW, height - textH, jiaodu);
                        }
                    }
                }
                // 添加水印文字
                under.endText();
                under.setLineWidth(1f);
                under.stroke();
            }
            stamper.close();
        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            reader.close();
        }
    }
//	public static void main(String[] args) {
//		Map<String,Object> syMap  = DbTool.getMapResult("SELECT COLOR,SETUP,SYNR,FONT,FONTSIZE,TRANSPARENCY,LINE,ROTATE FROM YQSY WHERE IS_DEL = 0 and STATUS= 1");
//		System.out.println(syMap);
//		syMap.put("SYNR","aaaa 中国农再档案 2023-09-08");
//		System.out.println(syMap);
//		pdfWaterMark("D:/test/第三方业务系统APi文档.pdf","D:/test/第三方业务系统APi文档01.pdf",syMap);
//	}
}
